package com.example.zxw.datalayer

import com.example.zxw.datalayer.source.NewsLocalSource
import com.example.zxw.datalayer.source.NewsNetSource
import com.example.zxw.entity.ChannelEntity
import com.example.zxw.entity.HotWordsEntity
import com.example.zxw.entity.NewsListEntity
import com.example.zxw.net.ApiResult
import com.example.zxw.net.result.CommonResult
import com.fmt.mvi.learn.gobal.log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class NewsRepo {

    private val newsNetSource by lazy { NewsNetSource() }
    private val newsLocalSource by lazy { NewsLocalSource() }


    suspend fun getHotWords(): CommonResult<List<HotWordsEntity>> {
        return withContext(Dispatchers.IO) {
            try {
                val data = newsNetSource.getHotWords("chs").transfrom()
                CommonResult.Success(data)
            } catch (e: Exception) {
                CommonResult.Error(e)
            }
        }
    }

    /**
     * 获取频道列表规则：
     * 本地有：先从本地取，然后在网络获取
     * 本地无：在网络获取->在更新到本地
     */
    suspend fun getChannelList(): CommonResult<List<ChannelEntity>> {
        return withContext(Dispatchers.IO) {
            try {
                val channelList = newsLocalSource.getChannelList()

                if (!channelList.isNullOrEmpty()) {
                    withContext(Dispatchers.IO) {
                        updateChannelList(null)
                    }
                    "11111".log()
                    CommonResult.Success(channelList)
                } else {
                    val data = newsNetSource.getChannelList().transfrom()
                    updateChannelList(data)
                    CommonResult.Success(data)
                }

            } catch (e: Exception) {
                CommonResult.Error(e)
            }
        }
    }

    suspend fun updateChannelList(netData: List<ChannelEntity>?) {
        val channelDatas = netData ?: newsNetSource.getChannelList().transfrom()
        val localData = newsLocalSource.getChannelList() as MutableList
        // 从旧数据中移除新数据中没有的频道
        var areadyHaveProvinceData = false
        if (localData.isNullOrEmpty()) {//第一次安装
            channelDatas.forEach {
                if ("yes" == it.isProvince) {//将地方数据 改为北京
                    it.cname = "beijing"
                    it.name = "北京"
                    it.fname = "北京"
                }
            }
            newsLocalSource.updateLocalChannelList(channelDatas)
        } else {
            val iterator = localData.iterator()
            while (iterator.hasNext()) {
                val current = iterator.next()
                //判断是否已经有了地方频道
                if ("yes" == current.isProvince) {
                    areadyHaveProvinceData = true
                    continue
                }
                if (!channelDatas.contains(current)) {
                    iterator.remove()
                }
            }
        }

        //遍历接口数据
        channelDatas.forEachIndexed { index, entity ->
            //如果不再旧数据列表,添加进来
            if (!localData.contains(entity)) {
                if ("yes" == entity.isProvince && !areadyHaveProvinceData) {
                    entity.cname = "beijing"
                    entity.name = "北京"
                    entity.fname = "北京"
                } else {
                    if (localData.size > index) {
                        localData.add(index, entity)
                    } else {
                        localData.add(entity)
                    }
                }

            } else {//如果已经存在该数据，则更新数据
                if ("yes" != entity.isProvince) {


                    val item = localData[localData.indexOf(entity)]
                    item.setName(entity.getName())
                    item.setFname(entity.getFname())
                    item.setContent(entity.getContent())
                    item.setImage(entity.getImage())
                    item.isNew = entity.getIsNew()
                    item.selectChsDay = entity.getSelectChsDay()
                    item.selectChsNight = entity.getSelectChsNight()
                    item.selectChtDay = entity.getSelectChtDay()
                    item.selectChtNight = entity.getSelectChtNight()
                    item.noSelectChsDay = entity.getNoSelectChsDay()
                    item.noSelectChsNight = entity.getNoSelectChsNight()
                    item.noSelectChtDay = entity.getNoSelectChtDay()
                    item.noSelectChtNight = entity.getNoSelectChtNight()
                    item.cardWord = entity.getCardWord()
                    item.isShowCardPic = entity.getIsShowCardPic()
                    item.isShare = entity.getIsShare()
                    item.pdShareUrl = entity.getPdShareUrl()
                    item.pdShareTitle = entity.getPdShareTitle()
                    item.pdShareFtTitle = entity.getPdShareFtTitle()
                    item.shareAbstract = entity.getShareAbstract()
                    item.shareFtAbstract = entity.getShareFtAbstract()
                    item.shareMinimg = entity.getShareMinimg()
                    item.shareCard = entity.getShareCard()
                    item.statusBar = entity.getStatusBar()
                    item.earthImg = entity.getEarthImg()
                    item.smallPlus = entity.getSmallPlus()
                    item.magnifierImg = entity.getMagnifierImg()
                    item.logoImg = entity.getLogoImg()
                    item.searchText = entity.getSearchText()
                    item.channelBackground = entity.getChannelBackground()
                    item.isHaveSub = entity.getIsHaveSub()
                    item.noSelectWordColor = entity.getNoSelectWordColor()
                    item.selectWordColor = entity.getSelectWordColor()
                    item.topBackground = entity.getTopBackground()
                    item.searchBackground = entity.getSearchBackground()
                    item.bgImage = entity.getBgImage()
                    item.pictureRatio = entity.getPictureRatio()
                    item.isControlStyle = entity.getIsControlStyle()
                    item.cutHomeImg = entity.getCutHomeImg()
                    item.refresh_icon_color = entity.getRefresh_icon_color()
                    item.loading_word_color = entity.getLoading_word_color()
                    item.isAsh = entity.isAsh
                }
            }
        }


        "2222222".log()

    }



    suspend fun getNewsListNet(cname: String,pageIndex: Int):ApiResult<List<NewsListEntity>>{
        return newsNetSource.getNewsList(cname, pageIndex)
    }

    fun getNewsListLocal(cname: String,pageIndex: Int):List<NewsListEntity>?{
        return newsLocalSource.getNewsList(cname, pageIndex)
    }


}